import React, { Component } from 'react';
import PropTypes from 'prop-types';
import { observer } from 'mobx-react';

import ContentLayout from '@/component/common/ContentLayout';
import MTable from '@/component/common/MTable';
import { Pagination, Form, Input, Select, DatePicker, message, Spin, Icon, Upload, Cascader, Rate, Checkbox } from 'antd';
import MModal from '@/component/common/MModal';
import OperModal from '@/component/common/OperModal';
import format from '@/tool/format';
import { broker_list_mini, repair_type, repair_address_list, add_repair_apply,
    cancel_repair_apply, upload_picture,
    repair_list, pay_repair, pass_broker_pay_apply, repair_evaluate_tags, repair_evaluate } from "@/constants/ApiTypes";
import { API_URL } from '@/config';
import helper from '@/tool/helper';

const FormItem = Form.Item;
const Option = Select.Option;
const mConfirm = MModal.confirm;
const { RangePicker } = DatePicker;
const { TextArea } = Input;
const LabelItem = OperModal.LabelItem;
const CheckboxGroup = Checkbox.Group;

import style from './style.scss';

import FilterListPage from '@/component/common/FilterListPage';
import ApiHelper from '@/store/ApiHelper';
import StoreListMini from '@/store/StoreListMini';
import BrokerListMini from '@/store/BrokerListMini';

// const testData = [
//     { a: 'HF1234567', b: '桂花城明月轩1栋2单元301室', c: '黄晓明', d: '12345678901', e: '2017/10/21 10:24', f: '空调不制冷', g: '吴超', h: '老铁', i: '12345678901', j: '待接单' },
//     { a: 'HF1234567', b: '桂花城明月轩1栋2单元301室', c: '黄晓明', d: '12345678901', e: '2017/10/21 10:24', f: '空调不制冷', g: '吴超', h: '老铁', i: '12345678901', j: '待接单' }
// ];

class ApplyRepairModal extends Component {
    constructor(props) {
        super(props);
    }
    static propTypes = {
        visible: PropTypes.bool,
        onClose: PropTypes.func.isRequired
    };
    defaultState = {
        store_id: '',
        broker_id: '',
        broker_list: [],
        house_no: '',
        address_list: [],
        content: '',
        spinning: false,
        previewVisible: false,
        previewImage: '',
        repair_type: '',
        images: '',
        fileList: []
    };
    state = {
        ...this.defaultState,
        repair_types: []
    };
    async componentDidMount() {
        this._isMounted = true;
        this._setState({ spinning: true });
        const result = await this.getRepairTypes();
        this._setState({
            spinning: false,
            repair_types: result.info
        });
    }
    componentWillUnmount() {
        this._isMounted = false;
    }
    //fix异步
    _setState = state => {
        if (this._isMounted) this.setState(state);
    };
    componentWillReceiveProps(nextProps) {
        if (nextProps.visible) {
            this.setState(this.defaultState);
        }
    }
    //获取维修类型
    getRepairTypes = () => {
        return ApiHelper.requestPost(repair_type, {}, true);
    };
    handleCancel = () => this.setState({ previewVisible: false });

    handlePreview = (file) => {
        this.setState({
            previewImage: file.url || file.thumbUrl,
            previewVisible: true
        });
    };
    handleChange = ({ fileList }) => {
        fileList = fileList.slice(0, 3);
        fileList.forEach((val, index) => {
            if (val.status == 'done' && val.response && !val.response.status) {
                fileList[index].status = 'error';
                MModal.success({ title: '上传失败', content: val.response.info, duration: 1.5 })
            }
        });
        this.fileChange(fileList);
        this.setState({ fileList });
    };
    //返回生成上传成功图片id数组
    fileChange = fileList => {
        let newFileList = [];
        fileList.forEach(val => {
            if (val.response && val.response.status) {
                newFileList.push(val.response.info[0].id);
            }
        });
        this.setState({ images: newFileList.join(',') });
    };
    submitBuyLock = async () => {
        const { store_id, broker_id, house_no, content, repair_type, images } = this.state;
        if (store_id == '') {
            return message.warn('请选择门店！', 1.5);
        }
        if (broker_id == '') {
            return message.warn('请选择经纪人！', 1.5);
        }
        if (house_no == '') {
            return message.warn('请选择地址！', 1.5);
        }
        if (repair_type == '' || !Array.isArray(repair_type)) {
            return message.warn('请选择维修类型！', 1.5);
        }
        if (format.trim(content) === '') {
            this.input_content.focus();
            return message.warn('请输入报修内容！', 1.5);
        }
        this._setState({ spinning: true });

        const data = {
            broker_id,
            repair_type: repair_type[1],
            house_no,
            content,
            images
        };

        const result = await ApiHelper.requestPost(add_repair_apply, data);
        this._setState({ spinning: false });
        if (result.status) {
            MModal.success({ title: '操作成功', content: '申请成功' });
            this.props.onClose();
        } else {
            MModal.success({ title: '操作失败', content: result.info });
        }
    };
    inputOnChange = e => {
        const name = e.target.name;
        const value = e.target.value;
        if (name == 'content') {
            this.setState({ content: value });
        }
    };
    selectStore = async value => {
        if (value == '') {
            return this._setState({ broker_list: [], store_id: value });
        }
        let data = { store_id: value };
        const result = await ApiHelper.requestPost(broker_list_mini, data);
        if (result.status) {
            this._setState({
                store_id: value,
                broker_id: '',
                broker_list: result.info,
                address_list: []
            });
        }
    };
    selectBroker = async value => {
        const data = { uid: value };
        const result = await ApiHelper.requestPost(repair_address_list, data);
        if (result.status) {
            this._setState({
                broker_id: value,
                address: '',
                address_list: result.info
            });
        }
    };
    selectAddress = value => {
        this._setState({ house_no: value });
    };
    onChangeRepairType = value => {
        this._setState({ repair_type: value });
    };
    render() {
        const { visible, onClose } = this.props;
        const { store_id, broker_id, house_no, repair_types, address_list, repair_type,
            broker_list, content, spinning, previewVisible, previewImage, fileList } = this.state;
        const { inputOnChange, handlePreview, handleChange } = this;
        const uploadButton = (
            <div>
                <Icon type="plus" />
                <div className="ant-upload-text">点击上传图片</div>
            </div>
        );

        const storeListMini = StoreListMini.info;

        let storeOptionList = storeListMini.map((val, index) => {
            return <Option key={index} value={`${val.store_id}`}>{val.store_name}</Option>;
        });
        let brokerOptionList = broker_list.map((val, index) => {
            return <Option key={index} value={`${val.uid}`}>{val.realname}</Option>;
        });
        let addressOptionList = address_list.map((val, index) => {
            return <Option key={index} value={val.house_no}>{val.address_detail}</Option>;
        });
        return (
            <MModal visible={visible} onClose={onClose} showMask closeMaskOnClick={false} width={815} height={helper.fixHeight(634)}>
                <Spin spinning={spinning} delay={150}>
                    <div className={style['apply-repair-modal']}>
                        <div className={style['select-wrap']}>
                            <div className={style['label-item']}>
                                <span className={style['label-text']}>门店：</span>
                                <Select placeholder="选择门店" style={{ width: 150 }} onChange={this.selectStore} value={store_id}>
                                    {storeOptionList}
                                </Select>
                            </div>
                            <div className={style['label-item']}>
                                <span className={style['label-text']}>经纪人：</span>
                                <Select placeholder="选择经纪人" style={{ width: 100 }} value={broker_id} onChange={this.selectBroker}>
                                    {brokerOptionList}
                                </Select>
                            </div>
                            <div className={style['label-item']}>
                                <span className={style['label-text']}>地址：</span>
                                <Select placeholder="选择地址" value={house_no} style={{ width: 260 }} onChange={this.selectAddress}>
                                    {addressOptionList}
                                </Select>
                            </div>
                        </div>
                        <div className={style['select-wrap']}>
                            <div className={style['label-item']}>
                                <span className={style['label-text']}>维修类型：</span>
                                <Cascader options={repair_types} onChange={this.onChangeRepairType} placeholder="请选择维修类型" value={repair_type} />
                            </div>
                        </div>
                        <div className={style['repair-content']}>
                            <h3>报修内容</h3>
                            <TextArea name="content" ref={input => this.input_content = input} placeholder="请输入报修内容" value={content} onChange={inputOnChange} />
                        </div>
                        <div className={style['repair-images']}>
                            <div className="repair-upload">
                                <Upload
                                    action={`${API_URL}/${upload_picture}`}
                                    listType="picture-card"
                                    fileList={fileList}
                                    onPreview={handlePreview}
                                    onChange={handleChange}
                                    multiple
                                    accept=".jpg, .png"
                                    name="image"
                                >
                                    {fileList.length >= 3 ? null : uploadButton}
                                </Upload>
                                <MModal visible={previewVisible} onClose={this.handleCancel} showMask width={520} height={520} zIndex={101}>
                                    <div className="image-preview-modal">
                                        <img alt="图片预览" src={previewImage} />
                                    </div>
                                </MModal>
                            </div>
                        </div>
                        <div className={style['submit']}>
                            <a href="javascript:void(0);" className={style['submit-btn']} onClick={this.submitBuyLock}>提交</a>
                        </div>
                    </div>
                </Spin>
            </MModal>
        );
    }
}

@observer class Filter extends Component {
    static propTypes = {
        form: PropTypes.any,
        applyClick: PropTypes.func.isRequired,
        onSubmit: PropTypes.func
    };
    handleSubmit = e => {
        e.preventDefault();
        this.props.form.validateFields((err, values) => {
            if (!err) {
                if (this.props.onSubmit) {
                    for (let key in values) {
                        if (values[key] === '') delete values[key];
                        //处理date_range
                        if (key == 'date_range') {
                            if (Array.isArray(values[key]) && values[key].length > 0) {
                                values.start_time = values[key][0].unix();
                                values.end_time =  values[key][1].unix();
                            }
                            delete values[key];
                        }
                    }
                    this.props.onSubmit(values);
                }
            }
        });
    };
    selectStore = value => {
        this.props.form.setFieldsValue({ broker_name: '' });
        if (value == '') {
            return BrokerListMini.info.clear();
        }
        BrokerListMini.getInfo(value);
    };
    render() {
        const { getFieldDecorator } = this.props.form;
        const storeListMini = StoreListMini.info;
        const brokerListMini = BrokerListMini.info;

        let storeOptionList = storeListMini.map((val, index) => {
            return <Option key={index} value={`${val.store_id}`}>{val.store_name}</Option>;
        });
        let brokerOptionList = brokerListMini.map((val, index) => {
            return <Option key={index} value={`${val.realname}`}>{val.realname}</Option>;
        });
        return (
            <Form layout="inline" onSubmit={this.handleSubmit}>
                <FormItem label="门店">
                    {getFieldDecorator('store_id', {
                        initialValue: ''
                    })(
                        <Select placeholder="选择门店" style={{ width: 150 }} onChange={this.selectStore}>
                            <Option key="default" value="">不限</Option>
                            {storeOptionList}
                        </Select>
                    )}
                </FormItem>
                <FormItem label="经纪人">
                    {getFieldDecorator('broker_name', {
                        initialValue: ''
                    })(
                        <Select placeholder="选择经纪人" style={{ width: 150 }}>
                            <Option key="default" value="">不限</Option>
                            {brokerOptionList}
                        </Select>
                    )}
                </FormItem>
                <FormItem label="时间">
                    {getFieldDecorator('date_range', {
                        initialValue: ''
                    })(
                        <RangePicker/>
                    )}
                </FormItem>
                <FormItem>
                    <button className={style['submit-btn']} type="submit">搜索</button>
                </FormItem>
                <FormItem>
                    <div className={style['filter-btn']} onClick={this.props.applyClick}><span className={style['filter-plus']} >+</span><span className={style['filter-buy']} href="javascript:void(0);">报修</span></div>
                </FormItem>
            </Form>
        );
    }
}
const FilterWrapped = Form.create()(Filter);

//维修评价模态框
class RepairEvaluateModal extends Component {
    constructor(props) {
        super(props);
    }
    static propTypes = {
        visible: PropTypes.bool,
        onClose: PropTypes.func.isRequired,
        repair_id: PropTypes.any.isRequired
    };
    defaultState = {
        valuate: 0,
        tags: []
    };
    state = { labelTags: [], ...this.defaultState };
    async componentDidMount() {
        this._isMounted = true;
        //获取评价标签
        const result = await ApiHelper.requestPost(repair_evaluate_tags);
        if (result.status) {
            this._setState({ labelTags: result.info });
        }
    }
    componentWillUnmount() {
        this._isMounted = false;
    }
    //fix异步
    _setState = state => {
        if (this._isMounted) this.setState(state);
    };
    componentWillReceiveProps(nextProps) {
        if (nextProps.visible) {
            this.setState(this.defaultState);
        }
    }
    submit = async () => {
        const { valuate, tags } = this.state;
        const { repair_id } = this.props;

        let _tags = tags.join(',');
        if (_tags == '') _tags = 0;

        const data = { valuate, tags: _tags, repair_id };
        const result = await ApiHelper.requestPost(repair_evaluate, data);
        if (result.status) {
            MModal.success({ title: '操作成功', content: '评价成功', duration: 1.5 });
            this.props.onClose(true);
        } else {
            MModal.success({ title: '操作失败', content: result.info });
        }
    };
    rateOnChange = value => {
        this.setState({ valuate: value });
    };
    checkOnChange = checkedValue => {
        this.setState({ tags: checkedValue });
    };
    render() {
        const { visible, onClose } = this.props;
        const { valuate, tags, labelTags } = this.state;
        const { submit, rateOnChange, checkOnChange } = this;
        const options = labelTags.map(val => ({ label: val.name, value: val.id }));
        return (
            <OperModal visible={visible} onClose={onClose} title="维修评价" width={330} height={180} onOk={submit}>
                <LabelItem width={66} align="right" label="评分">
                    <Rate value={valuate} onChange={rateOnChange}/>
                </LabelItem>
                <LabelItem width={66} align="right" label="标签" labelStyle={{ float: 'left' }}>
                    <div style={{ width: 200, display: 'inline-block' }}>
                        <CheckboxGroup value={tags} options={options} onChange={checkOnChange} />
                    </div>
                </LabelItem>
            </OperModal>
        );
    }
}

@observer class RepairList extends FilterListPage {
    constructor(props) {
        super(props);
        const state = {
            applyRepairModalVisible: false,
            repairEvaluateModalVisible: false,
            repairEvaluateProps: {
                repair_id: 0
            }
        };
        this.listApiType = repair_list;
        this._setDefaultState(state);
    }
    async pageDidMount() {
        const result = await StoreListMini.getInfo();
        if (!result) return;
        this._setState({ loading: false });
    }
    showApplyRepairModal = () => {
        this._setState({ applyRepairModalVisible: true });
    };
    closeApplyRepairModal = () => {
        this._setState({ applyRepairModalVisible: false });
    };
    showRepairEvaluateModalModal = repair_id => {
        this._setState({
            repairEvaluateModalVisible: true,
            repairEvaluateProps: {
                repair_id
            }
        });
    };
    closeRepairEvaluateModalModal = () => {
        this._setState({ repairEvaluateModalVisible: false });
    };
    cancelRepairApply = apply_id => {
        mConfirm({
            title: '是否取消该维修申请？',
            titleStyle: { fontSize: 16 },
            width: 300,
            height: 177,
            content: '',
            okText: '是',
            cancelText: '否',
            okClassName: 'primary-btn-ok',
            cancelClassName: 'primary-btn-cancel',
            showTopClose: false,
            onOk: async () => {
                const data = { apply_id };
                const result = await ApiHelper.requestPost(cancel_repair_apply, data);
                if (result.status) {
                    MModal.success({ title: '操作成功', content: '取消成功', duration: 1.5 });
                    //刷新列表 //关闭当前模态框
                    this.refresh();
                } else {
                    MModal.success({ title: '操作失败', content: result.info });
                }
            },
            onCancel() { }
        });
    };
    //支付维修
    payRepair = (item_id, pay_apply = false) => {
        mConfirm({
            title: '确定要支付该维修吗',
            titleStyle: { fontSize: 16 },
            width: 300,
            height: 177,
            content: '',
            okText: '是',
            cancelText: '否',
            okClassName: 'primary-btn-ok',
            cancelClassName: 'primary-btn-cancel',
            showTopClose: false,
            onOk: async () => {
                let data, api_type;
                if (pay_apply) {
                    //通过经纪人支付申请
                    data = { apply_id: item_id, apply_status: 1 };
                    api_type = pass_broker_pay_apply;
                } else {
                    //联盟店自己支付
                    data = { repair_id: item_id };
                    api_type = pay_repair;
                }

                const result = await ApiHelper.requestPost(api_type, data);
                if (result.status) {
                    MModal.success({ title: '操作成功', content: '支付成功', duration: 1.5 });
                    //刷新列表 //关闭当前模态框
                    this.refresh();
                } else {
                    MModal.success({ title: '操作失败', content: result.info });
                }
            },
            onCancel() { }
        });
    };
    //否决经纪人支付维修申请
    rejectBrokerPay = apply_id => {
        mConfirm({
            title: '确定要否决该支付申请吗',
            titleStyle: { fontSize: 16 },
            width: 300,
            height: 177,
            content: '',
            okText: '是',
            cancelText: '否',
            okClassName: 'primary-btn-ok',
            cancelClassName: 'primary-btn-cancel',
            showTopClose: false,
            onOk: async () => {
                const data = { apply_id: apply_id, apply_status: 2 };
                const result = await ApiHelper.requestPost(pass_broker_pay_apply, data);
                if (result.status) {
                    MModal.success({ title: '操作成功', content: '否决成功', duration: 1.5 });
                    //刷新列表 //关闭当前模态框
                    this.refresh();
                } else {
                    MModal.success({ title: '操作失败', content: result.info });
                }
            },
            onCancel() { }
        });
    };
    render() {
        const { applyRepairModalVisible, repairEvaluateModalVisible, repairEvaluateProps, dataList, spinning } = this.state;
        const { showApplyRepairModal, closeApplyRepairModal, closeRepairEvaluateModalModal } = this;
        const repair_state = (text, record, dataIndex) => {
            if (record.ra_status == -1) return '已取消';
            const types = ['待接单', '已接单', '维修中', '已完成'];
            const type = types[record.ra_status];
            let ret = '';
            switch (type) {
            case '待接单':
                ret = '待接单';
                break;
            case '已接单':
                ret = '已接单';
                break;
            case '维修中':
                ret = '维修中';
                break;
            case '已完成':
                if (!record.is_pay) {
                    if (record.pay_apply == 1) {
                        //经纪人申请的支付
                        if (record.pay_apply_status == 2) {
                            ret = '支付申请已否决';
                        }
                        else if (record.pay_apply_status == 0) {
                            ret = <a href="javascript:void(0);" onClick={() => this.payRepair(record.pay_apply_id, true)}>通过支付</a>;
                        }
                    } else {
                        //后台添加的维修申请
                        ret = <a href="javascript:void(0);" onClick={() => this.payRepair(record.repair_apply_id)}>去支付</a>;
                    }
                } else {
                    ret = '已完成';
                }
                break;
            }
            return ret;
        };
        const repair_oper = (text, record, dataIndex) => {
            const types = ['待接单', '已接单', '维修中', '已完成'];
            const type = types[record.ra_status];
            let ret = '无';
            switch (type) {
            case '待接单':
                ret = <a href="javascript:void(0);" onClick={() => this.cancelRepairApply(record.repair_apply_id)}>取消</a>;
                break;
            case '已接单':
                break;
            case '维修中':
                break;
            case '已完成':
                if (!record.is_pay && record.pay_apply == 1 && record.pay_apply_status == 0)
                    ret = <a href="javascript:void(0);" onClick={() => this.rejectBrokerPay(record.pay_apply_id, true)}>否决支付申请</a>;
                if (record.is_pay && record.pay_apply == 0)
                    ret = <a href="javascript:void(0);" onClick={() => this.showRepairEvaluateModalModal(record.repair_apply_id)}>去评价</a>;
                break;
            }
            return ret;
        };
        const columns = [
            { title: '编号', dataIndex: 'repair_apply_id', align: 'middle' },
            { title: '报修地址', dataIndex: 'address', align: 'middle' },
            { title: '租客', dataIndex: 'renter_name', align: 'middle' },
            { title: '电话', dataIndex: 'renter_mobile', align: 'middle' },
            { title: '报修时间', dataIndex: 'create_time', align: 'middle', render: (text, record, dataIndex) => format.timeString(text) },
            { title: '报修内容', dataIndex: 'content', render: (text, record, dataIndex) => `[${record.repair_name}]${text}` },
            { title: '经纪人', dataIndex: 'broker_name', align: 'middle' },
            { title: '维修师傅', dataIndex: 'worker_name', align: 'middle' },
            { title: '师傅电话', dataIndex: 'worker_mobile', align: 'middle' },
            { title: '维修金额', dataIndex: 'repair_money', align: 'middle', render: (text, record, dataIndex) => !isNaN(text) ? text / 100 + '元' : text },
            { title: '状态', dataIndex: 'j', align: 'middle', render: repair_state },
            { title: '操作', dataIndex: 'k', align: 'middle', render: repair_oper }
        ];
        return (
            <ContentLayout navTitle="维修" loading={this.state.loading}>
                <div className={style['top-wrap']}>
                    <div className={style['top-filter']}>
                        <FilterWrapped onSubmit={this.getDataListWithFilter} applyClick={showApplyRepairModal} />
                        <ApplyRepairModal visible={applyRepairModalVisible} onClose={closeApplyRepairModal} />
                    </div>
                    <div className={style['top-total']}>
                        <span>维修金额：{this.state.result_info.total_price / 100}元</span><span>维修：{this.state.result_info.count_over}套</span>
                    </div>
                    <MTable columns={columns} dataSource={dataList} spinning={spinning}/>
                    <RepairEvaluateModal visible={repairEvaluateModalVisible} onClose={closeRepairEvaluateModalModal} {...repairEvaluateProps} />
                    <div className="pagination">
                        {this.state.total > 0 && <Pagination showQuickJumper current={this.state.current_page} pageSize={10} total={this.state.total} onChange={this.pageOnChange} />}
                    </div>
                </div>
            </ContentLayout>
        );
    }
}

export default RepairList;